from odoo import models, _
from odoo.exceptions import UserError
import requests
import json


class SbMESUpload(models.AbstractModel):
    _name = 's.mes.upload'

    def upload_data(self, data):
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        # and data.get('docType', False) != 'BS_WP'
        result = None
        if not mes_enabled:
            self.env['api.records'].create({
                'doc_type': data.get('docType', ''),
                'api_route': '请先配置在: s.api.config_parameter表中配置参数: mes.enabled',
                'api_params': str(data),
                'result_json': '',
                'state': 'fail'
            })
            return
        url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')], limit=1).s_value
        if not url:
            self.env['api.records'].create({
                'doc_type': data.get('docType', ''),
                'api_route': '请先配置在: s.api.config_parameter表中配置参数: mes.updateImsData',
                'api_params': str(data),
                'result_json': '',
                'state': 'fail'
            })
            return
        try:
            token = self.env['s.mes.login'].sudo().get_mes_token()
            if not token:
                return
            headers = {
                'Content-Type': 'application/json',
                'accessToken': token,
            }
            res = requests.post(url, json=data, headers=headers)
            result = res.json()
            if result.get('resultCode') != '0000':  # 请求失败
                self.env['api.records'].create({
                    'doc_type': data.get('docType', ''),
                    'api_route': url,
                    'api_params': str(data),
                    'result_json': str(result),
                    'state': 'fail'
                })
            else:
                self.env['api.records'].create({
                    'doc_type': data.get('docType', ''),
                    'api_route': url,
                    'api_params': str(data),
                    'result_json': str(result),
                    'state': 'success'
                })
        except Exception as e:
            self.env['api.records'].create({
                'doc_type': data.get('docType', ''),
                'api_route': url,
                'api_params': str(data),
                'result_json': e,
                'state': 'fail'
            })
        return result

    def wms_upload_data(self, data, api_address, url=None):
        """发送数据并记录日志
        wms.BaseUrl： "http://192.168.1.1:60041",  最后必须是/
        """
        record_val = {}
        if not self.s_check_allow(): return
        try:
            base_url = self.env['s.api.config_parameter'].search([('s_key', '=', 'wms.BaseUrl')], limit=1).s_value
            url = base_url + api_address
            headers = {'Content-Type': 'application/json'}
            res = requests.post(url, json=data, headers=headers)
            result = res.json()
            if result.get('IsSuccess') and not int(result.get('code')):
                record_val = {
                    'doc_type': api_address, 'api_route': url, 'api_params': str(data),
                    'result_json': str(result), 'state': 'success'}
            else:
                record_val = {
                    'doc_type': api_address, 'api_route': url, 'api_params': str(data),
                    'result_json': str(result), 'state': 'fail'}
        except Exception as e:
            record_val = {
                'doc_type': api_address, 'api_route': url, 'api_params': str(data),
                'result_json': e, 'state': 'fail'}
        self.env['api.records'].create(record_val)
        return record_val


    def s_check_allow(self):
        """校验接口是否开通、以及url是否配置"""
        wms_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'wms.enabled')], limit=1).s_value
        url = self.env['s.api.config_parameter'].search([('s_key', '=', 'wms.BaseUrl')], limit=1).s_value
        error_vals = {}
        if not wms_enabled:
            error_vals = {
                'doc_type': 'CustomerData-客户/供应商接口',
                'api_route': '请先配置在: s.api.config_parameter表中配置参数: wms.enabled',
                'api_params': None,
                'result_json': '',
                'state': 'fail'
            }
        elif not url:
            error_vals = {
                'doc_type': 'CustomerData-客户/供应商接口',
                'api_route': '请先配置在: s.api.config_parameter表中配置参数: wms.BaseUrl',
                'api_params': None,
                'result_json': '',
                'state': 'fail'
            }
        if error_vals:
            self.env['api.records'].create(error_vals)
            return False
        else:
            return True

